import {
    serializeGetParams,
    isAbsolutePath,
    _checkIsPromise
} from '../../util'
export function fetchPost(config) {
    // debugger
    const _url = isAbsolutePath(config.url) ? config.url : config.baseURL.concat(config.url)
    // const _url = config.baseURL.concat(config.url)
    let headers = {
        ...config.headers,
    }

    return new Promise((resolve, reject) => {
        fetch(_url, {
                method: config.method,
                body: JSON.stringify(config.data),
                mode: config.mode || 'cors',
                cache: config.cache || 'no-cache',
                credentials: config.withCredentials ? 'include' : (config.credentials || 'same-origin'),
                headers: new Headers(headers)
            }).then((response) => {
                if (response.ok) {
                    return response.json()
                } else {
                    let err = {
                        status: response.status,
                        message: response.statusText
                    }
                    reject(err)
                }
            })
            .then(res => {
                resolve(res)
            })
            .catch(err => {
                let errs = {
                    status: err.status,
                    message: err.statusText
                }
                reject(errs)
            })
    })
}

export async function fectGet(config) {
    console.log(config)
    // debugger
    return new Promise((resolve, reject) => {
        const _serializeParams = config.data && Object.keys(config.data).length > 0 ? serializeGetParams(config.data) : ''
        const _url = config.baseURL.concat(config.url, _serializeParams)
        let headers = {
            ...config.headers,
        }
        console.log('fetch-----config---', config)
        fetch(_url, {
                method: config.method,
                mode: config.mode || 'cors',
                cache: config.cache || 'no-cache',
                credentials: config.withCredentials ? 'include' : (config.credentials || 'same-origin'),
                headers: new Headers(headers)
            }).then(response => {
                console.log(response)
                if (response.ok) {
                    return response.json()
                } else {
                    let err = {
                        status: response.status,
                        message: response.statusText
                    }
                    reject(err)
                }
            }).then(res => {
                resolve(res)
            })
            .catch(err => {
                let errs = {
                    status: err.status,
                    message: err.statusText
                }
                reject(errs)
            })

        // .catch(responseErr => {
        //     console.log('responseErr----------', responseErr)
        //     reject(responseErr)
        // })
    })
}